<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--考勤数据-->
        <pane size="84">
          <el-col>
            <!-- 月度考勤搜索区域 -->
            <el-card class="box-card" style="margin-bottom: 20px;">
              <div slot="header" class="clearfix">
                <span>月度考勤查询</span>
              </div>
              <el-form :model="monthlyQueryParams" ref="monthlyQueryForm" size="small" :inline="true" label-width="80px">
                <el-form-item label="工号" prop="searchUserId">
                  <el-input
                    v-model="monthlyQueryParams.searchUserId"
                    placeholder="请输入工号"
                    clearable
                    style="width: 200px;"
                    @keyup.enter.native="handleMonthlyQuery"
                  />
                </el-form-item>
                <el-form-item label="查询月份" prop="searchMonth">
                  <el-date-picker
                    v-model="monthlyQueryParams.searchMonth"
                    type="month"
                    value-format="yyyy-MM"
                    placeholder="请选择月份"
                    style="width: 200px;"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMonthlyQuery">查询</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetMonthlyQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 月度考勤表格 -->
            <el-card v-if="showMonthlyTable" class="box-card" style="margin-bottom: 20px;">
              <div slot="header" class="clearfix">
                <span v-if="currentUser">
                  工号: {{ monthlyQueryParams.searchUserId }} | 姓名: {{ currentUser.nickName || currentUser.userName }} | {{ monthlyQueryParams.searchMonth }} 考勤记录
                </span>
                <span v-else>
                  工号: {{ monthlyQueryParams.searchUserId }} - {{ monthlyQueryParams.searchMonth }} 考勤记录
                </span>
              </div>
              <div class="monthly-attendance-table">
                <el-table :data="monthlyAttendanceData" border style="width: 100%">
                  <el-table-column label="日期" prop="date" width="100" align="center" />
                  <el-table-column label="星期" prop="weekday" width="80" align="center" />
                  <el-table-column label="打卡状态" prop="status" align="center">
                    <template slot-scope="scope">
                      <el-tag 
                        :type="getStatusType(scope.row.status)"
                        :style="{ backgroundColor: getStatusColor(scope.row.status), color: '#fff' }"
                      >
                        {{ scope.row.statusText }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" prop="remark" align="center" />
                </el-table>
              </div>
            </el-card>

            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="打卡日期" prop="punchDate">
        <el-date-picker clearable
          v-model="queryParams.punchDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择打卡日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="备用字段 aa" prop="aa">
        <el-input
          v-model="queryParams.aa"
          placeholder="请输入备用字段 aa"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备用字段 bb" prop="bb">
        <el-input
          v-model="queryParams.bb"
          placeholder="请输入备用字段 bb"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备用字段 cc" prop="cc">
        <el-input
          v-model="queryParams.cc"
          placeholder="请输入备用字段 cc"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:attendance:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:attendance:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:attendance:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:attendance:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="用户ID" align="center" prop="userId" /> -->
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="工号" align="center" prop="employeeId">
        <template slot-scope="scope">
          <span>{{ scope.row.employeeId || '无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="打卡日期" align="center" prop="punchDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.punchDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上班情况" align="center" prop="aa" />
      <el-table-column label="备用字段 bb" align="center" prop="bb" />
      <el-table-column label="备用字段 cc" align="center" prop="cc" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:attendance:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:attendance:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  
<!-- 添加或修改考勤信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="打卡日期" prop="punchDate">
          <el-date-picker clearable
            v-model="form.punchDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择打卡日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备用字段 aa" prop="aa">
          <el-input v-model="form.aa" placeholder="请输入备用字段 aa" />
        </el-form-item>
        <el-form-item label="备用字段 bb" prop="bb">
          <el-input v-model="form.bb" placeholder="请输入备用字段 bb" />
        </el-form-item>
        <el-form-item label="备用字段 cc" prop="cc">
          <el-input v-model="form.cc" placeholder="请输入备用字段 cc" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
  </div>
</template>

<script>
import { listAttendance, getAttendance, delAttendance, addAttendance, updateAttendance } from "@/api/system/attendance";
import { deptTreeSelect, getUserByEmployeeId } from "@/api/system/user";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "Attendance",
  components: {
    Splitpanes,
    Pane
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考勤信息表格数据
      attendanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,
        punchDate: null,
        aa: null,
        bb: null,
        cc: null,
        deptId: undefined
      },
      // 月度查询参数
      monthlyQueryParams: {
        searchUserId: '',
        searchMonth: ''
      },
      // 月度考勤数据
      monthlyAttendanceData: [],
      // 是否显示月度表格
      showMonthlyTable: false,
      // 当前查询的用户信息
      currentUser: null,
      // 表单参数
      form: {},
      // 部门树选项
      deptOptions: [],
      // 部门名称
      deptName: undefined,
      // 树结构数据
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        punchDate: [
          { required: true, message: "打卡日期不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    // 设置默认查询月份为当前月
    this.monthlyQueryParams.searchMonth = this.getCurrentMonth();
  },
  methods: {
    /** 获取当前月份 */
    getCurrentMonth() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}`;
    },
    /** 生成指定月份的所有日期 */
    generateMonthDays(yearMonth) {
      const [year, month] = yearMonth.split('-').map(Number);
      const daysInMonth = new Date(year, month, 0).getDate();
      const days = [];
      
      for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(year, month - 1, day);
        const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
        
        days.push({
          date: dateStr,
          weekday: `周${weekdays[date.getDay()]}`,
          status: 'none',
          statusText: '未打卡',
          remark: ''
        });
      }
      
      return days;
    },
    /** 获取状态颜色 */
    getStatusColor(status) {
      switch (status) {
        case 'work':
          return '#67C23A'; // 绿色 - 业务员打卡并上班
        case 'punch':
          return '#E6A23C'; // 黄色 - 业务员打卡
        case 'none':
        default:
          return '#FFFFFF'; // 白色 - 未打卡
      }
    },
    /** 获取状态类型 */
    getStatusType(status) {
      switch (status) {
        case 'work':
          return 'success';
        case 'punch':
          return 'warning';
        case 'none':
        default:
          return 'info';
      }
    },
    /** 月度考勤查询 */
    async handleMonthlyQuery() {
      if (!this.monthlyQueryParams.searchUserId || !this.monthlyQueryParams.searchMonth) {
        this.$message.warning('请输入工号和选择月份');
        return;
      }
      
      try {
        // 先根据工号查询用户信息
        const userResponse = await getUserByEmployeeId(this.monthlyQueryParams.searchUserId);
        if (!userResponse.data) {
          this.$message.error('未找到该工号对应的用户');
          return;
        }
        
        const user = userResponse.data;
        console.log('找到用户:', user);
        
        // 生成月份所有日期
        const monthDays = this.generateMonthDays(this.monthlyQueryParams.searchMonth);
        
        // 查询该用户的考勤数据
        const queryParams = {
          userId: user.userId,
          startDate: `${this.monthlyQueryParams.searchMonth}-01`,
          endDate: `${this.monthlyQueryParams.searchMonth}-${monthDays.length}`
        };
        
        const attendanceResponse = await listAttendance(queryParams);
        const attendanceData = attendanceResponse.rows || [];
        
        // 将考勤数据映射到日期表格
        monthDays.forEach(day => {
          const attendance = attendanceData.find(item => item.punchDate === day.date);
          if (attendance) {
            if (attendance.aa === '业务员打卡并上班') {
              day.status = 'work';
              day.statusText = '已上班';
            } else if (attendance.aa === '业务员打卡') {
              day.status = 'punch';
              day.statusText = '已打卡';
            } else {
              day.status = 'punch';
              day.statusText = '已打卡';
            }
            day.remark = attendance.aa || '';
          }
        });
        
        this.monthlyAttendanceData = monthDays;
        this.showMonthlyTable = true;
        
        // 更新表格标题显示用户信息
        this.currentUser = user;
        
      } catch (error) {
        console.error('查询月度考勤失败:', error);
        this.$message.error('查询失败，请重试');
      }
    },
    /** 重置月度查询 */
    resetMonthlyQuery() {
      this.monthlyQueryParams.searchUserId = '';
      this.monthlyQueryParams.searchMonth = this.getCurrentMonth();
      this.showMonthlyTable = false;
      this.monthlyAttendanceData = [];
      this.currentUser = null;
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      console.log('选择部门:', data.label, '部门ID:', data.id);
      this.handleQuery();
    },
    /** 查询考勤信息列表 */
    getList(pagination) {
      this.loading = true;
      // 如果传入了分页参数，更新查询参数
      if (pagination) {
        this.queryParams.pageNum = pagination.page;
        this.queryParams.pageSize = pagination.limit;
      }
      listAttendance(this.queryParams).then(response => {
        this.attendanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        userName: null,
        punchDate: null,
        aa: null,
        bb: null,
        cc: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考勤信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAttendance(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考勤信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAttendance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttendance(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除考勤信息编号为"' + ids + '"的数据项？').then(function() {
        return delAttendance(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/attendance/export', {
        ...this.queryParams
      }, `attendance_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.monthly-attendance-table {
  margin-top: 10px;
}

.box-card {
  margin-bottom: 20px;
}

.el-tag {
  border: none;
}
</style>
